package com.jjty.dataGenerator.sxhcampus.controller;


import com.alibaba.fastjson.JSONObject;
import com.jjty.dataGenerator.common.ApiResult;
import com.jjty.dataGenerator.exception.ServiceException;
import com.jjty.dataGenerator.sxhcampus.ApiCallSxHcampus;
import com.jjty.dataGenerator.sxhcampus.SxHCampusConfig;
import com.jjty.dataGenerator.sxhcampus.service.SxHCampusService;
import com.jjty.dataGenerator.sxhcampus.utils.Coder;
import com.jjty.dataGenerator.sxhcampus.vo.*;
import com.jjty.dataGenerator.utils.TimeUtils;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author: huangyulong
 * @createTime: 2023-11-08 15:38
 * @Description:
 */
@RestController
@RequestMapping("/supply/sxHCampus")
public class SxHCampusController {

    @Autowired
    private SxHCampusService sxHCampusService;

    @Autowired
    private ApiCallSxHcampus apiCallSxHcampus;


    @RequestMapping("doTest")
    public ApiResult doTest() throws UnsupportedEncodingException {
        EsActiveData randomData = sxHCampusService.getRandomData();
        String concatStr = Coder.getConcatStr(randomData);
        String s = Coder.hmac_sha1(concatStr, SxHCampusConfig.appkey);
        s = new BigInteger(s.getBytes("UTF-8")).toString();
        System.out.println(concatStr);
        System.out.println(s);
        randomData.setSig(s);
        try{
            BaseResultSx baseResultSx = apiCallSxHcampus.sendActiveData(randomData);
            return ApiResult.querySuccess(baseResultSx);
        }catch (ServiceException e){
            return ApiResult.doFailure(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return ApiResult.doFailure(e.getMessage());
        }
    }


    /**
     * 导入并发送活跃数据
     * @return
     */
    @RequestMapping("importActiveData")
    public ApiResult importActiveData(MultipartFile file,String agentId){
        sxHCampusService.importActiveData(file,agentId);
        return ApiResult.doSuccess("成功");
    }


    @RequestMapping("testFormat")
    public ApiResult testFormat(){
        String jsonstr = "{\n" +
                "    \"code\": 0,\n" +
                "    \"msg\": \"\",\n" +
                "    \"count\": 1,\n" +
                "    \"data\": [\n" +
                "        {\n" +
                "            \"id\": 573566,\n" +
                "            \"hall_name\": \"阳峪网格\",\n" +
                "            \"hall_addr\": \"咸阳市乾县阳峪网格\",\n" +
                "            \"hall_id\": 0,\n" +
                "            \"ymd\": 20240424,\n" +
                "            \"did\": 17,\n" +
                "            \"user_id\": 65,\n" +
                "            \"user_name\": \"王益峰\",\n" +
                "            \"order_phone\": \"18700054098\",\n" +
                "            \"package\": \"20档月包\",\n" +
                "            \"firm\": \"\",\n" +
                "            \"firm_phone\": \"\",\n" +
                "            \"wechat_id\": \"\",\n" +
                "            \"counterpart\": \"雷雨\",\n" +
                "            \"counterpart_name\": null,\n" +
                "            \"city\": \"咸阳市\",\n" +
                "            \"district\": \"乾　县\",\n" +
                "            \"red_packet\": \"20.00\",\n" +
                "            \"reward\": \"0.00\",\n" +
                "            \"remark\": \"王魁，吴敏\",\n" +
                "            \"stored_fee\": \"100.00\",\n" +
                "            \"device_type\": 3,\n" +
                "            \"device\": \"862247061965764\",\n" +
                "            \"status\": 0,\n" +
                "            \"is_check\": 0,\n" +
                "            \"is_withdrawal\": 0,\n" +
                "            \"file_path\": \"\",\n" +
                "            \"device_type1\": 0,\n" +
                "            \"device1\": \"\",\n" +
                "            \"type\": 0,\n" +
                "            \"is_combined\": 2,\n" +
                "            \"is_repeat\": 0,\n" +
                "            \"create_time\": \"2024-04-24\",\n" +
                "            \"update_time\": 1713967535,\n" +
                "            \"delete_time\": 0,\n" +
                "            \"creator\": \"董梦娇\",\n" +
                "            \"device_title\": \"腕表\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        OAQueryOrderResult oaQueryOrderResult = JSONObject.parseObject(jsonstr, OAQueryOrderResult.class);
        return ApiResult.querySuccess(oaQueryOrderResult);
    }

    /**
     * 同步活跃数据模版,截止到上一天
     * 从2023.8.1开始
     * @return
     */
    @RequestMapping("syncActiveTemplateAll")
    public ApiResult syncActiveTemplateAll() {
        Date today = new Date();
        Date startDate = TimeUtils.getDate(2023, 8, 1);
        //参数，开始日期
        String startTime = "";
        int duringCount = 0;
        //如果开始时间>=今天
        while (startDate.before(today)){
            //拿到yyyyMMdd格式的日期字符串
            startTime = TimeUtils.getFormat("yyyyMMdd", startDate);
            //provinceId=610000  查询陕西市
            //获取时间范围内的数据
            HttpResponse<String> httpResponse = Unirest.get("https://oa.jiajiasports.com/openapi/order/listWithDate?startTime="+startTime+"&endTime="+startTime+"&provinceId=610000")
                    .asString();
            String body = httpResponse.getBody();
            OAQueryOrderResult result = JSONObject.parseObject(body, OAQueryOrderResult.class);
            duringCount = result.getData().size();
            System.out.println("日期："+startTime+" --- 数据条数："+duringCount);
            startDate = TimeUtils.addDate(startDate,1,Calendar.DATE);
            if(duringCount == 0){
                continue;
            }
            sxHCampusService.syncActiveTemplateAll(startTime,result.getData());
        }
        return ApiResult.doSuccess("数据同步完成");
    }


    /**
     * 同步某一天的数据
     * @return
     */
    @RequestMapping("syncActiveTemplateForDay")
    public ApiResult syncActiveTemplateForDay(String date){
        if(StringUtils.isBlank(date)){
            date = TimeUtils.getFormat("yyyyMMdd");
        }
        HttpResponse<String> httpResponse = Unirest.get("https://oa.jiajiasports.com/openapi/order/listWithDate?startTime="+date+"&endTime="+date+"&provinceId=610000")
                .asString();
        String body = httpResponse.getBody();
        OAQueryOrderResult result = JSONObject.parseObject(body, OAQueryOrderResult.class);
        int duringCount = result.getData().size();
        if(duringCount == 0)return ApiResult.doFailure("当日无新增活跃");
        sxHCampusService.syncActiveTemplateForDay(result.getData(),date);
        return ApiResult.doSuccess("当日活跃同步完成");
    }


    //获取前一天的数据
    @RequestMapping("importActiveDataAll")
    public ApiResult importActiveDataAll() {
        try {
            // 获取前一天的日期
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_YEAR, -1);
            Date yesterday = calendar.getTime();
            String yesterdayStr = TimeUtils.getFormat("yyyyMMdd", yesterday);

            // 前一天的开始时间和结束时间相同
            String startTime = yesterdayStr;
            String endTime = yesterdayStr;
            String batchNumber = "All" + yesterdayStr;

            // provinceId=610000 查询陕西市
            // 获取前一天的数据
            HttpResponse<String> httpResponse = Unirest.get("https://oa.jiajiasports.com/openapi/order/listWithDate?startTime=" + startTime + "&endTime=" + endTime + "&provinceId=610000")
                    .asString();
            String body = httpResponse.getBody();
            OAQueryOrderResult result = JSONObject.parseObject(body, OAQueryOrderResult.class);

            // 调用 importActiveDataAll 方法
            sxHCampusService.importActiveDataAll(result, startTime, endTime, batchNumber);

            return ApiResult.doSuccess("成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.doFailure(e.getMessage());
        }
    }

    /**
     * 获取全部日期的数据并导入
     * @return ApiResult
     */
    @RequestMapping("importAllDatesActiveData")
    public ApiResult importAllDatesActiveData() {
        try {
            // 开始日期设置为 2023 年 8 月 1 日
            Calendar startCalendar = Calendar.getInstance();
            startCalendar.set(2023, Calendar.AUGUST, 1);
            Date startDate = startCalendar.getTime();

            // 获取当前日期
            Calendar currentCalendar = Calendar.getInstance();
            Date currentDate = currentCalendar.getTime();

            // 遍历从开始日期到当前日期，每次跨度为 7 天
            while (startDate.before(currentDate) || startDate.equals(currentDate)) {
                Calendar endCalendar = Calendar.getInstance();
                endCalendar.setTime(startDate);
                endCalendar.add(Calendar.DAY_OF_YEAR, 7);
                Date endDate = endCalendar.getTime();
                if (endDate.after(currentDate)) {
                    endDate = currentDate;
                }

                // 检查是否跨月，如果跨月则将 endDate 设置为当月最后一天
                if(!TimeUtils.isSameMonth(startDate,endDate)){
                    endDate = TimeUtils.getLastDayOfMonth(startDate);
                }

                String startTime = TimeUtils.getFormat("yyyyMMdd", startDate);
                String endTime = TimeUtils.getFormat("yyyyMMdd", endDate);
                String batchNumber = "All" + startTime + "~" + endTime;

                // provinceId=610000 查询陕西市
                // 获取指定日期范围的数据
                HttpResponse<String> httpResponse = Unirest.get("https://oa.jiajiasports.com/openapi/order/listWithDate?startTime=" + startTime + "&endTime=" + endTime + "&provinceId=610000")
                        .asString();
                String body = httpResponse.getBody();
                OAQueryOrderResult result = JSONObject.parseObject(body, OAQueryOrderResult.class);

                // 调用 importActiveDataAll 方法
                sxHCampusService.importActiveDataAll(result, startTime, endTime, batchNumber);

                // 更新开始日期为下一个 7 天的起始日期
                startCalendar.setTime(endDate);
                startCalendar.add(Calendar.DAY_OF_YEAR, 1);
                startDate = startCalendar.getTime();
            }

            return ApiResult.doSuccess("全部日期数据导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.doFailure(e.getMessage());
        }
    }

    @RequestMapping("transformAndSaveAllData")
    public ApiResult transformAndSaveAllData() {
        try {
            sxHCampusService.transformAndSaveAllData();
            return ApiResult.doSuccess("数据转换并保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.doFailure(e.getMessage());
        }
    }

    @RequestMapping("sendAllActiveData")
    public ApiResult sendAllActiveData() {
        try {
            sxHCampusService.sendAllActiveData();
            return ApiResult.querySuccess("所有活跃数据发送成功");
        } catch (ServiceException e) {
            return ApiResult.doFailure(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.doFailure("发送活跃数据时出现未知异常：" + e.getMessage());
        }
    }
}